// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.JoinModel;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.entity.AmazonSettlementReport;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.AmazonSettlementReportMapper;
import com.fowo.api.mapper.ShopInfoMapper;
import com.fowo.api.mapper.SysCountryMapper;
import com.fowo.api.model.amazon.settlement.report.AmazonSettlementReportExcelPo;
import com.fowo.api.model.amazon.settlement.report.AmazonSettlementReportImportPo;
import com.fowo.api.model.amazon.settlement.report.AmazonSettlementReportItemVo;
import com.fowo.api.model.amazon.settlement.report.AmazonSettlementReportSearchParamPo;
import com.fowo.api.model.amazon.settlement.report.AmazonSettlementReportVo;
import com.fowo.api.model.shop.info.ShopInfoItemVo;
import com.fowo.api.model.shop.info.ShopInfoSearchParamPo;
import com.fowo.api.model.sys.country.SysCountryItemVo;
import com.fowo.api.model.sys.country.SysCountrySearchParamPo;
import com.fowo.api.service.AmazonSettlementReportService;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.model.SysDictAllItem;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysDictService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 亚马逊结算中心-交易明细 服务实现基类
 * @author 蜂窝蜜造平台 配置人：鹿丙涛，任凯
 */
@Slf4j
@DataObjectType(AmazonSettlementReport.class)
@DS("ds24")
public class AmazonSettlementReportBaseServiceImpl
  extends ServiceImpl<AmazonSettlementReportMapper, AmazonSettlementReport>
  implements AmazonSettlementReportService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("sidShopName", "si.`shop_name`");
      put("countryCodeCountry", "sc.`country`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected AmazonSettlementReportService self;

  @Resource
  private SysDictService sysDictService;

  @Resource
  protected ShopInfoMapper shopInfoMapper;

  @Resource
  protected SysCountryMapper sysCountryMapper;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  protected WorkFlowService workFlowService;

  @Resource
  protected Validator validator;

  /**
   * 创建亚马逊结算中心-交易明细
   * @param model 亚马逊结算中心-交易明细
   * @return 新数据的主键
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(AmazonSettlementReportVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    AmazonSettlementReport entity = new AmazonSettlementReport();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.save(entity)) {
      return entity.getId();
    }
    throw new Exception("亚马逊结算中心-交易明细保存失败");
  }

  /**
   * 更新亚马逊结算中心-交易明细
   * @param model 亚马逊结算中心-交易明细
   * @return 更新是否成功
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(AmazonSettlementReportVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    AmazonSettlementReport entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("亚马逊结算中心-交易明细不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "createTime",
      "createUser",
      "lastUpdateTime",
      "lastUpdateUser"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      return true;
    }
    return false;
  }/**
   * 更新亚马逊结算中心-交易明细（带空值）
   * @param model 亚马逊结算中心-交易明细
   * @return 更新是否成功
   */

  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(AmazonSettlementReportVo model)
    throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    AmazonSettlementReport entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("亚马逊结算中心-交易明细不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(AmazonSettlementReport::getAmazonOrderId, model.getAmazonOrderId())
      .set(AmazonSettlementReport::getSid, model.getSid())
      .set(AmazonSettlementReport::getStoreName, model.getStoreName())
      .set(AmazonSettlementReport::getSellerId, model.getSellerId())
      .set(AmazonSettlementReport::getCountryCode, model.getCountryCode())
      .set(AmazonSettlementReport::getAccountType, model.getAccountType())
      .set(AmazonSettlementReport::getFulfillment, model.getFulfillment())
      .set(AmazonSettlementReport::getLastUpdateTime, model.getLastUpdateTime())
      .set(AmazonSettlementReport::getLastUpdateUser, model.getLastUpdateUser())
      .set(AmazonSettlementReport::getEventType, model.getEventType())
      .set(AmazonSettlementReport::getSellerSku, model.getSellerSku())
      .set(AmazonSettlementReport::getType, model.getType())
      .set(
        AmazonSettlementReport::getPostedDateLocale,
        model.getPostedDateLocale()
      )
      .set(AmazonSettlementReport::getCurrencyCode, model.getCurrencyCode())
      .set(AmazonSettlementReport::getCurrencyAmount, model.getCurrencyAmount())
      .set(AmazonSettlementReport::getQuantity, model.getQuantity())
      .set(
        AmazonSettlementReport::getProcessingStatus,
        model.getProcessingStatus()
      )
      .set(
        AmazonSettlementReport::getFundTransferStatus,
        model.getFundTransferStatus()
      )
      .set(AmazonSettlementReport::getFid, model.getFid())
      .set(AmazonSettlementReport::getSettlementId, model.getSettlementId())
      .set(AmazonSettlementReport::getLocalSku, model.getLocalSku())
      .set(AmazonSettlementReport::getLocalName, model.getLocalName())
      .set(AmazonSettlementReport::getGmtModified, model.getGmtModified())
      .set(
        AmazonSettlementReport::getMerchantOrderItemId,
        model.getMerchantOrderItemId()
      )
      .set(
        AmazonSettlementReport::getMarketplaceName,
        model.getMarketplaceName()
      )
      .set(
        AmazonSettlementReport::getFinancialEventGroupId,
        model.getFinancialEventGroupId()
      )
      .eq(AmazonSettlementReport::getId, model.getId())
      .update();
    if (isOk) {}
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(
    AmazonSettlementReportSearchParamPo search
  ) {
    return false;
  }

  /**
   * 删除亚马逊结算中心-交易明细
   * @param id 亚马逊结算中心-交易明细的主键
   * @return 删除是否成功
   */
  @Override
  public boolean delete(Long id) throws Exception {
    return this.removeById(id);
  }

  /**
   * 批量删除亚马逊结算中心-交易明细
   * @param ids 亚马逊结算中心-交易明细的主键列表
   * @return 删除是否成功
   */
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @param allowOverrides 允许覆盖
   * @return 导入行对象
   */
  protected ImportRow<AmazonSettlementReportImportPo> excelToImportRow(
    AmazonSettlementReportImportPo row,
    Integer rowNumber,
    AmazonSettlementReportVo vo,
    Map<String, Object> variables,
    boolean allowOverrides
  ) {
    ImportRow<AmazonSettlementReportImportPo> ir =
      new ImportRow<AmazonSettlementReportImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<AmazonSettlementReportImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new AmazonSettlementReportVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, AmazonSettlementReportImportPo.class);

    // 一般数据处理
    if (StringUtils.hasText(row.getAccountType())) {
      List<SysDictAllItem> accountTypeItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "accountType",
          n -> sysDictService.getDictItems(" SCM00233")
        );
      AmazonSettlementReportVo finalVo = vo;
      accountTypeItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getAccountType()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setAccountType(i.getItemValue()),
          () ->
            ir.addError(
              "accountType",
              String.format(
                "必须为 %s 中之一",
                accountTypeItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getEventType())) {
      List<SysDictAllItem> eventTypeItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "eventType",
          n -> sysDictService.getDictItems("SCM00214")
        );
      AmazonSettlementReportVo finalVo = vo;
      eventTypeItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getEventType()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setEventType(i.getItemValue()),
          () ->
            ir.addError(
              "eventType",
              String.format(
                "必须为 %s 中之一",
                eventTypeItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getType())) {
      List<SysDictAllItem> typeItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "type",
          n -> sysDictService.getDictItems("SCM00234")
        );
      AmazonSettlementReportVo finalVo = vo;
      typeItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getType()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setType(i.getItemValue()),
          () ->
            ir.addError(
              "type",
              String.format(
                "必须为 %s 中之一",
                typeItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setPostedDateLocale(SheetUtils.tryToDateTime(row.getPostedDateLocale()));
    if (StringUtils.hasText(row.getCurrencyCode())) {
      List<SysDictAllItem> currencyCodeItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "currencyCode",
          n -> sysDictService.getDictItems("SCM00015")
        );
      AmazonSettlementReportVo finalVo = vo;
      currencyCodeItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getCurrencyCode()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setCurrencyCode(i.getItemValue()),
          () ->
            ir.addError(
              "currencyCode",
              String.format(
                "必须为 %s 中之一",
                currencyCodeItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setCurrencyAmount(SheetUtils.tryToDecimal(row.getCurrencyAmount()));
    vo.setQuantity(SheetUtils.tryToInteger(row.getQuantity()));
    if (StringUtils.hasText(row.getProcessingStatus())) {
      List<SysDictAllItem> processingStatusItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "processingStatus",
          n -> sysDictService.getDictItems("SCM00216")
        );
      AmazonSettlementReportVo finalVo = vo;
      processingStatusItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getProcessingStatus()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setProcessingStatus(i.getItemValue()),
          () ->
            ir.addError(
              "processingStatus",
              String.format(
                "必须为 %s 中之一",
                processingStatusItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getFundTransferStatus())) {
      List<SysDictAllItem> fundTransferStatusItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "fundTransferStatus",
          n -> sysDictService.getDictItems("SCM00217")
        );
      AmazonSettlementReportVo finalVo = vo;
      fundTransferStatusItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getFundTransferStatus()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setFundTransferStatus(i.getItemValue()),
          () ->
            ir.addError(
              "fundTransferStatus",
              String.format(
                "必须为 %s 中之一",
                fundTransferStatusItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setGmtModified(SheetUtils.tryToDateTime(row.getGmtModified()));
    // 处理关联字段“店铺”
    if (
      !SheetUtils.isBlank(row.getSidShopName()) &&
      SheetUtils.isBlank(row.getSid())
    ) {
      ShopInfoSearchParamPo sidSearchParam = new ShopInfoSearchParamPo();
      sidSearchParam.setLimit(2); // 最大只返回二行记录
      sidSearchParam.setShopNameEq(SheetUtils.trim(row.getSidShopName()));
      sidSearchParam.applySqlSegments();
      List<ShopInfoItemVo> sidMatches = shopInfoMapper.search(sidSearchParam);
      if (sidMatches.size() == 0) {
        ir.addError("sidShopName", "未能在店铺中找到匹配的数据");
      } else if (sidMatches.size() > 1) {
        ir.addError("sidShopName", "关联不唯一，在店铺中找到多个匹配的数据");
      } else {
        vo.setSid(sidMatches.get(0).getId());
      }
    }
    // 处理关联字段“国家”
    if (
      !SheetUtils.isBlank(row.getCountryCodeCountry()) &&
      SheetUtils.isBlank(row.getCountryCode())
    ) {
      SysCountrySearchParamPo countryCodeSearchParam =
        new SysCountrySearchParamPo();
      countryCodeSearchParam.setLimit(2); // 最大只返回二行记录
      countryCodeSearchParam.setCountryEq(
        SheetUtils.trim(row.getCountryCodeCountry())
      );
      countryCodeSearchParam.applySqlSegments();
      List<SysCountryItemVo> countryCodeMatches = sysCountryMapper.search(
        countryCodeSearchParam
      );
      if (countryCodeMatches.size() == 0) {
        ir.addError("countryCodeCountry", "未能在国家中找到匹配的数据");
      } else if (countryCodeMatches.size() > 1) {
        ir.addError(
          "countryCodeCountry",
          "关联不唯一，在国家中找到多个匹配的数据"
        );
      } else {
        vo.setCountryCode(countryCodeMatches.get(0).getId());
      }
    }

    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   * @param templateId 要使用的模版编号
   * @param allowOverrides 允许覆盖
   */
  @Override
  public List<ImportRow<AmazonSettlementReportImportPo>> importPreview(
    SysFile sysFile,
    Long templateId,
    boolean allowOverrides
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<AmazonSettlementReportImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            AmazonSettlementReportImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(
              AmazonSettlementReportImportPo row,
              AnalysisContext cxt
            ) {
              AmazonSettlementReportVo vo = new AmazonSettlementReportVo();
              ImportRow<AmazonSettlementReportImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                vo,
                variables,
                allowOverrides
              );
              if (ir.isEmptyRow()) {
                return;
              }
              if (allowOverrides) {
                // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(
    List<ImportRow<AmazonSettlementReportImportPo>> rows,
    Long templateId
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    String sysImportBatchNo = StrUtil.concat(
      true,
      DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN),
      IdUtil.nanoId(4)
    );
    List<Long> importedIdList = new ArrayList<>();
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<AmazonSettlementReportImportPo> row = rows.get(i);
      Long updateId = row.getUpdateId();
      AmazonSettlementReportVo vo = new AmazonSettlementReportVo();
      row =
        excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      if (updateId != null) {
        vo.setId(updateId);
      }
      SheetUtils.setSysImportTemplateName(
        vo,
        null == importTemplate ? "默认模板" : importTemplate.getTitle()
      );
      SheetUtils.setSysImportBatchNo(vo, sysImportBatchNo);
      if (updateId == null) {
        importedIdList.add(create(vo));
      } else {
        self.update(vo);
        importedIdList.add(vo.getId());
      }
    }
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @Override
  public void export(
    Long templateId,
    AmazonSettlementReportSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addFieldMappingOption(
        "sid",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((AmazonSettlementReportItemVo) r).getSidShopName())
          )
      );
      exportOptions.addFieldMappingOption(
        "countryCode",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((AmazonSettlementReportItemVo) r).getCountryCodeCountry()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "accountType",
        new CustomExcelExport.FieldMappingOption().setDictCode(" SCM00233")
      );
      exportOptions.addFieldMappingOption(
        "eventType",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00214")
      );
      exportOptions.addFieldMappingOption(
        "type",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00234")
      );
      exportOptions.addFieldMappingOption(
        "currencyCode",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00015")
      );
      exportOptions.addFieldMappingOption(
        "processingStatus",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00216")
      );
      exportOptions.addFieldMappingOption(
        "fundTransferStatus",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00217")
      );
      exportOptions.addStringFields(
        "amazonOrderId",
        "sidShopName",
        "storeName",
        "sellerId",
        "countryCodeCountry",
        "accountType",
        "fulfillment",
        "eventType",
        "sellerSku",
        "type",
        "currencyCode",
        "processingStatus",
        "fundTransferStatus",
        "fid",
        "settlementId",
        "localSku",
        "localName",
        "merchantOrderItemId",
        "marketplaceName",
        "financialEventGroupId"
      );

      String fileName = String.format(
        "亚马逊结算中心-交易明细(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    List<SysDictAllItem> accountTypeItems = sysDictService.getDictItems(
      " SCM00233"
    );
    List<SysDictAllItem> eventTypeItems = sysDictService.getDictItems(
      "SCM00214"
    );
    List<SysDictAllItem> typeItems = sysDictService.getDictItems("SCM00234");
    List<SysDictAllItem> currencyCodeItems = sysDictService.getDictItems(
      "SCM00015"
    );
    List<SysDictAllItem> processingStatusItems = sysDictService.getDictItems(
      "SCM00216"
    );
    List<SysDictAllItem> fundTransferStatusItems = sysDictService.getDictItems(
      "SCM00217"
    );
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<AmazonSettlementReportExcelPo> items =
      new ArrayList<AmazonSettlementReportExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<AmazonSettlementReportItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<AmazonSettlementReportItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (AmazonSettlementReportItemVo item : list) {
        AmazonSettlementReportExcelPo excel =
          new AmazonSettlementReportExcelPo();
        BeanUtils.copyProperties(item, excel);
        if (item.getAccountType() != null) {
          accountTypeItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getAccountType()))
            .findFirst()
            .ifPresent(i -> excel.setAccountType(i.getItemText()));
        }
        if (item.getEventType() != null) {
          eventTypeItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getEventType()))
            .findFirst()
            .ifPresent(i -> excel.setEventType(i.getItemText()));
        }
        if (item.getType() != null) {
          typeItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getType()))
            .findFirst()
            .ifPresent(i -> excel.setType(i.getItemText()));
        }
        if (item.getCurrencyCode() != null) {
          currencyCodeItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getCurrencyCode()))
            .findFirst()
            .ifPresent(i -> excel.setCurrencyCode(i.getItemText()));
        }
        if (item.getProcessingStatus() != null) {
          processingStatusItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getProcessingStatus()))
            .findFirst()
            .ifPresent(i -> excel.setProcessingStatus(i.getItemText()));
        }
        if (item.getFundTransferStatus() != null) {
          fundTransferStatusItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getFundTransferStatus()))
            .findFirst()
            .ifPresent(i -> excel.setFundTransferStatus(i.getItemText()));
        }

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "亚马逊结算中心-交易明细(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(AmazonSettlementReportExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过财务事件组id查询亚马逊结算中心-交易明细主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByFinancialEventGroupId(String financialEventGroupId) {
    return this.baseMapper.getIdByFinancialEventGroupId(financialEventGroupId);
  }

  /**
   * 通过财务事件组id查询亚马逊结算中心-交易明细多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByFinancialEventGroupId(List<String> list) {
    return this.baseMapper.getIdsByFinancialEventGroupId(list);
  }

  /**
   * 通过亚马逊结算中心-交易明细主键查询财务事件组id
   */
  @Override
  public String getFinancialEventGroupIdById(Long id) {
    return this.baseMapper.getFinancialEventGroupIdById(id);
  }

  /**
   * 通过亚马逊结算中心-交易明细主键查询财务事件组id列表
   */
  @Override
  public List<String> getFinancialEventGroupIdByIds(List<Long> ids) {
    List<Map<String, Object>> maps =
      this.baseMapper.getFinancialEventGroupIdByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap ->
            (String) stringObjectMap.get("financialEventGroupId")
          )
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 亚马逊结算中心-交易明细的主键
   */
  @Override
  public AmazonSettlementReportVo getVoById(Long id) throws Exception {
    AmazonSettlementReportVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }
    return vo;
  }

  /**
   * 分页查询亚马逊结算中心-交易明细
   * @param search 查询条件
   * @return 亚马逊结算中心-交易明细分页查询结果
   */
  @Override
  public Page<AmazonSettlementReportItemVo> pageSearch(
    AmazonSettlementReportSearchParamPo search
  ) {
    Page<AmazonSettlementReportItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(AmazonSettlementReportItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 亚马逊结算中心-交易明细快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'AmazonSettlementReportOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<AmazonSettlementReportItemVo>> searchOptions(
    AmazonSettlementReportSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询亚马逊结算中心-交易明细
   * @param search 查询条件
   * @return 亚马逊结算中心-交易明细列表查询结果
   */
  @Override
  public List<AmazonSettlementReportItemVo> search(
    AmazonSettlementReportSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询亚马逊结算中心-交易明细最后更新时间
   * @param search 查询条件
   * @return 亚马逊结算中心-交易明细最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(AmazonSettlementReportSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 看板
   */
  @Override
  public List<AmazonSettlementReportItemVo> bulletinBoard(
    AmazonSettlementReportSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.bulletinBoard(search);
  }

  /**
   * 看板分页
   */
  @Override
  public Page<AmazonSettlementReportItemVo> bulletinBoardPage(
    AmazonSettlementReportSearchParamPo search
  ) {
    Page<AmazonSettlementReportItemVo> bulletinBoardPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return bulletinBoardPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return bulletinBoardPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    bulletinBoardPage =
      this.baseMapper.bulletinBoardPage(
          search.toPage(this.baseMapper.bulletinBoardCount(search)),
          search
        );
    List<Long> recordIds = bulletinBoardPage
      .getRecords()
      .stream()
      .map(AmazonSettlementReportItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return bulletinBoardPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return bulletinBoardPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    bulletinBoardPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return bulletinBoardPage;
  }

  /**
   * 查询看板最后更新时间
   * @param search 查询条件
   * @return 看板最后更新时间
   */
  @Override
  public Date bulletinBoardLastUpdateTime(
    AmazonSettlementReportSearchParamPo search
  ) {
    return this.baseMapper.bulletinBoardLastUpdateTime(search);
  }

  /**
   * 结算汇总
   */
  @Override
  public List<AmazonSettlementReportItemVo> settlementSummary(
    AmazonSettlementReportSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.settlementSummary(search);
  }

  /**
   * 结算汇总分页
   */
  @Override
  public Page<AmazonSettlementReportItemVo> settlementSummaryPage(
    AmazonSettlementReportSearchParamPo search
  ) {
    Page<AmazonSettlementReportItemVo> settlementSummaryPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return settlementSummaryPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return settlementSummaryPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    settlementSummaryPage =
      this.baseMapper.settlementSummaryPage(
          search.toPage(this.baseMapper.settlementSummaryCount(search)),
          search
        );
    List<Long> recordIds = settlementSummaryPage
      .getRecords()
      .stream()
      .map(AmazonSettlementReportItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return settlementSummaryPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return settlementSummaryPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    settlementSummaryPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return settlementSummaryPage;
  }

  /**
   * 查询结算汇总最后更新时间
   * @param search 查询条件
   * @return 结算汇总最后更新时间
   */
  @Override
  public Date settlementSummaryLastUpdateTime(
    AmazonSettlementReportSearchParamPo search
  ) {
    return this.baseMapper.settlementSummaryLastUpdateTime(search);
  }

  /**
   * 交易明细
   */
  @Override
  public List<AmazonSettlementReportItemVo> transactionDetails(
    AmazonSettlementReportSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.transactionDetails(search);
  }

  /**
   * 交易明细分页
   */
  @Override
  public Page<AmazonSettlementReportItemVo> transactionDetailsPage(
    AmazonSettlementReportSearchParamPo search
  ) {
    Page<AmazonSettlementReportItemVo> transactionDetailsPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return transactionDetailsPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return transactionDetailsPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    transactionDetailsPage =
      this.baseMapper.transactionDetailsPage(
          search.toPage(this.baseMapper.transactionDetailsCount(search)),
          search
        );
    List<Long> recordIds = transactionDetailsPage
      .getRecords()
      .stream()
      .map(AmazonSettlementReportItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return transactionDetailsPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return transactionDetailsPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    transactionDetailsPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return transactionDetailsPage;
  }

  /**
   * 查询交易明细最后更新时间
   * @param search 查询条件
   * @return 交易明细最后更新时间
   */
  @Override
  public Date transactionDetailsLastUpdateTime(
    AmazonSettlementReportSearchParamPo search
  ) {
    return this.baseMapper.transactionDetailsLastUpdateTime(search);
  }
}
